package com.xk857.simpleeffect.fragment;

import static android.content.Context.MODE_PRIVATE;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.igexin.sdk.PushManager;
import com.xk857.simpleeffect.AppNoticeActivity;
import com.xk857.simpleeffect.MainActivity;
import com.xk857.simpleeffect.R;
import com.xk857.simpleeffect.domain.Result;
import com.xk857.simpleeffect.domain.entity.Customer;
import com.xk857.simpleeffect.domain.param.LoginParam;
import com.xk857.simpleeffect.domain.vo.LoginCode;
import com.xk857.simpleeffect.enums.RequestEnum;
import com.xk857.simpleeffect.utils.OkHttpUtils;
import com.xuexiang.xui.widget.toast.XToast;

import java.lang.reflect.Type;
import java.util.function.Consumer;

import cn.hutool.core.util.StrUtil;

public class LoginFragment extends Fragment {

    View view;
    private String uuid;
    // 验证码图片
    private ImageView codeImgView;

    private Consumer<Integer> consumer;
    private EditText phoneEdit;
    private EditText pwdEdit;
    private EditText authCodeEdit;
    private String initUsername;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_login, container, false);
        codeImgView = view.findViewById(R.id.code_img);
        codeImgView.setOnClickListener(v -> getAuthCode());
        getAuthCode();
        jumpPage();
        initView();
        return view;
    }

    private void initView() {
        Button loginButton = view.findViewById(R.id.login_btn);
        phoneEdit = view.findViewById(R.id.phone_edit);
        if (StrUtil.isNotBlank(initUsername)) {
            phoneEdit.setText(initUsername);
        }
        pwdEdit = view.findViewById(R.id.pwd_edit);
        authCodeEdit = view.findViewById(R.id.auth_code_edit);
        loginButton.setOnClickListener(v -> {
            if (getActivity() != null) {
                if (StrUtil.hasBlank(phoneEdit.getText())) {
                    XToast.normal(getActivity(), "请输入手机号").show();
                    return;
                }
                if (StrUtil.hasBlank(pwdEdit.getText())) {
                    XToast.normal(getActivity(), "请输入密码").show();
                    return;
                }
                if (StrUtil.hasBlank(authCodeEdit.getText())) {
                    XToast.normal(getActivity(), "请输入验证码").show();
                    return;
                }
                LoginParam loginParam = new LoginParam();
                loginParam.setCode(String.valueOf(authCodeEdit.getText()));
                loginParam.setPassword(String.valueOf(pwdEdit.getText()));
                loginParam.setUsername(String.valueOf(phoneEdit.getText()));
                loginParam.setUuid(uuid);

                Type type = new TypeToken<Result<Customer>>() {}.getType();
                OkHttpUtils.getInstance().post(getActivity(), RequestEnum.LOGIN, type, loginParam, true, (Consumer<Customer>) customer -> {
                    Gson gson = new Gson();
                    SharedPreferences preferences = getActivity().getSharedPreferences("userInfo", MODE_PRIVATE);
                    SharedPreferences.Editor edit = preferences.edit();
                    edit.putString("token", customer.getToken());
                    edit.putString("customer", gson.toJson(customer));
                    edit.apply();//提交

                    getActivity().runOnUiThread(() -> {
                        // 请求，绑定cid
                        String clientId = PushManager.getInstance().getClientid(getActivity());
                        String url = OkHttpUtils.BASE_URL + "/api/v1/customer/bound/push/" + clientId;
                        Type type1 = new TypeToken<Result<Boolean>>() {
                        }.getType();
                        OkHttpUtils.getInstance().get(getActivity(), url, type1, false, (Consumer<Boolean>) b -> {
                            getActivity().runOnUiThread(() -> {
                                getActivity().startActivity(new Intent(getActivity(), MainActivity.class));
                                getActivity().finish();
                            });
                        });
                    });
                });
            }
        });

        TextView userAboutText = view.findViewById(R.id.user_about_text);
        TextView privateAboutText = view.findViewById(R.id.private_about_text);
        userAboutText.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), AppNoticeActivity.class);
            intent.putExtra("isPrivate", false);
            startActivity(intent);
        });
        privateAboutText.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), AppNoticeActivity.class);
            intent.putExtra("isPrivate", true);
            startActivity(intent);
        });
    }

    // 负责按钮页面跳转
    private void jumpPage() {
        Button forgetBtn = view.findViewById(R.id.forget_password_btn);
        Button registerBtn = view.findViewById(R.id.register_btn);
        registerBtn.setOnClickListener(v -> consumer.accept(0));
        forgetBtn.setOnClickListener(v -> consumer.accept(1));
    }

    /**
     * 获取验证码并显示
     */
    private void getAuthCode() {
        Type type = new TypeToken<Result<LoginCode>>() {
        }.getType();
        OkHttpUtils.getInstance().post(getActivity(), RequestEnum.LOGIN_CODE, type, null, false, (Consumer<LoginCode>) loginCode -> {
            uuid = loginCode.getUuid();
            // 解析出Base64编码的图片数据
            String imageDataBytes = loginCode.getCodeUrl().substring(loginCode.getCodeUrl().indexOf(",") + 1);
            byte[] imageBytes = Base64.decode(imageDataBytes, Base64.DEFAULT);
            // 将字节数组转换为Bitmap对象
            Bitmap bmp = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);

            // 显示图片
            if (getActivity() != null) {
                getActivity().runOnUiThread(() -> {
                    codeImgView.setImageBitmap(bmp);
                });
            }
        });
    }

    public void setOnClickListener(Consumer<Integer> consumer) {
        this.consumer = consumer;
    }

    public void setInitUsername(String initUsername) {
        this.initUsername = initUsername;
    }
}
